package com.codeduck.account.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codeduck.account.domain.AccountDO;
import com.codeduck.account.mapper.AccountMapper;
import com.codeduck.account.service.IAccountService;
import com.codeduck.common.enums.MicroExceptionEnum;
import com.codeduck.common.exception.MicroException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2022-08-19
 */
@Service
@Slf4j
public class AccountServiceImpl extends ServiceImpl<AccountMapper, AccountDO> implements IAccountService {
    @Override
    public AccountDO decreaseAccount(String userId, BigDecimal money) {
        QueryWrapper<AccountDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AccountDO::getUserId, userId);
        AccountDO account = this.getOne(wrapper);
        if (Objects.isNull(account)) {
            throw new MicroException(MicroExceptionEnum.PARAM_ERROR.getMessage());
        }
        // 更新金额
        account.setMoney(account.getMoney().subtract(money));
        int update = this.baseMapper.update(account, wrapper);
        if (update > 0) {
            AccountDO one = this.getOne(Wrappers.<AccountDO>lambdaQuery().eq(AccountDO::getId, userId));
            log.info("扣费成功！当前用户账号数据：[{}]", JSON.toJSONString(one));
            return account;
        }

        throw new MicroException(MicroExceptionEnum.DECREASE_ACCOUNT_FAIL.getMessage());
    }
}
